#include "app_eeprom_manage.h"
#include "EEPROM.h"  // 真EEPROM接口 (I2C, PE4/PE5)
#include "usart4.h"  // for UART5_Printf debug
#include "flow.h"


/* ===================== 函数实现 ===================== */

/**
 * @brief  从EEPROM加载数据
 * @param  None
 * @retval None
 * @note   系统初始化时调用,加载历史数据到g_user_config
 */
void app_eeprom_load_data(void)
{
    EepromData_t eeprom_data;
    u8 valid_flag;

    // 步骤1: 读取有效标志
    valid_flag = EEPROM_ReadByte(EEPROM_ADDR_DATA_VALID_FLAG);

    // 步骤2: 检查数据是否有效
    if (valid_flag == EEPROM_DATA_VALID_FLAG_VALUE)
    {
        // 数据有效,读取UV工作时间(旧)
        EEPROM_ReadMulti(EEPROM_ADDR_UV_WORKTIME,
                         (u8*)&eeprom_data.uv_work_time_sec,
                         sizeof(u32));

        // 读取累计流量
        EEPROM_ReadMulti(EEPROM_ADDR_TOTAL_FLOW,
                         (u8*)&eeprom_data.total_flow_liters,
                         sizeof(float));

        // 更新到全局配置
        g_user_config.uv_work_time_sec = eeprom_data.uv_work_time_sec;
        g_user_config.flow_total = eeprom_data.total_flow_liters;

        // 同步到流量计全局变量
        golbal_flow.acculat = eeprom_data.total_flow_liters;

        // 检查UV灯寿命警告
        if (g_user_config.uv_work_time_sec >= UV_LIFETIME_SECONDS)
        {
            g_user_config.uv_lifetime_warning = 1;
        }

        #if DEBUG_APP_ENABLE
        u32 hours = g_user_config.uv_work_time_sec / 3600;
        UART5_Printf("[EEPROM] Loaded - UV Time: %lu hours, Flow: %.2f L\r\n",
                     hours, g_user_config.flow_total);
        #endif
    }
    else
    {
        // 数据无效,使用默认值(已在user_config_init中初始化)
        #if DEBUG_APP_ENABLE
        UART5_Printf("[EEPROM] No valid data, using defaults\r\n");
        #endif
    }

    // ========== 新增: 加载UV控制状态机相关数据 ==========
    // 检查UV数据有效标志位
    u8 uv_valid_flag = EEPROM_ReadByte(EEPROM_ADDR_UV_DATA_VALID_FLAG);

    if (uv_valid_flag == EEPROM_UV_DATA_VALID_FLAG_VALUE)
    {
        // UV数据有效,加载数据
        g_user_config.uv_total_work_hours = app_eeprom_read_uv_worktime();
        g_user_config.uv_ignore_flag1 = app_eeprom_get_ignore_flag(1);
        g_user_config.uv_ignore_flag2 = app_eeprom_get_ignore_flag(2);

        #if DEBUG_APP_ENABLE
        UART5_Printf("[EEPROM] UV State - Hours: %lu, Ignore1: %d, Ignore2: %d\r\n",
                     g_user_config.uv_total_work_hours,
                     g_user_config.uv_ignore_flag1,
                     g_user_config.uv_ignore_flag2);
        #endif
    }
    else
    {
        // UV数据无效,使用默认值(已在user_config_init中初始化为0)
        #if DEBUG_APP_ENABLE
        UART5_Printf("[EEPROM] UV State - No valid UV data (flag=0x%02X), using defaults\r\n", uv_valid_flag);
        #endif
    }
}


/**
 * @brief  保存数据到EEPROM
 * @param  None
 * @retval 0=成功, 1=失败
 * @note   将g_user_config中的数据保存到EEPROM,并通过回读验证
 */
u8 app_eeprom_save_data(void)
{
    EepromData_t eeprom_data;
    EepromData_t verify_data;
    u8 verify_flag;

    // 准备数据
    eeprom_data.uv_work_time_sec = g_user_config.uv_work_time_sec;
    eeprom_data.total_flow_liters = golbal_flow.acculat;  // 使用流量计的累计值
    eeprom_data.valid_flag = EEPROM_DATA_VALID_FLAG_VALUE;

    // 写入UV工作时间
    EEPROM_WriteMulti(EEPROM_ADDR_UV_WORKTIME,
                      (u8*)&eeprom_data.uv_work_time_sec,
                      sizeof(u32));

    // 写入累计流量
    EEPROM_WriteMulti(EEPROM_ADDR_TOTAL_FLOW,
                      (u8*)&eeprom_data.total_flow_liters,
                      sizeof(float));

    // 写入有效标志
    EEPROM_WriteByte(EEPROM_ADDR_DATA_VALID_FLAG,
                     eeprom_data.valid_flag);

    // ========== 新增: 回读验证 ==========
    verify_flag = EEPROM_ReadByte(EEPROM_ADDR_DATA_VALID_FLAG);
    EEPROM_ReadMulti(EEPROM_ADDR_UV_WORKTIME,
                     (u8*)&verify_data.uv_work_time_sec,
                     sizeof(u32));
    EEPROM_ReadMulti(EEPROM_ADDR_TOTAL_FLOW,
                     (u8*)&verify_data.total_flow_liters,
                     sizeof(float));

    // 验证数据是否正确写入
    u8 verify_success = 1;
    if (verify_flag != EEPROM_DATA_VALID_FLAG_VALUE)
    {
        verify_success = 0;
        UART5_Printf("[EEPROM] Verify FAILED - Valid flag mismatch!\r\n");
    }
    if (verify_data.uv_work_time_sec != eeprom_data.uv_work_time_sec)
    {
        verify_success = 0;
        UART5_Printf("[EEPROM] Verify FAILED - UV time mismatch!\r\n");
    }
    if (verify_data.total_flow_liters != eeprom_data.total_flow_liters)
    {
        verify_success = 0;
        UART5_Printf("[EEPROM] Verify FAILED - Flow mismatch!\r\n");
    }

    // 更新上次保存时间戳
    g_user_config.last_save_time_sec = g_user_config.system_tick_sec;

    // 清除需要保存标志
    g_user_config.need_save_flag = 0;

    // 打印保存结果
    #if DEBUG_APP_ENABLE
    u32 hours = g_user_config.uv_work_time_sec / 3600;
    if (verify_success)
    {
        UART5_Printf("[EEPROM] Saved & Verified OK - UV Time: %lu hours, Flow: %.2f L\r\n",
                     hours, eeprom_data.total_flow_liters);
    }
    else
    {
        UART5_Printf("[EEPROM] Saved but Verify FAILED!\r\n");
    }
    #else
    // 即使不开启调试,也要打印验证结果
    if (verify_success)
    {
        u32 hours = g_user_config.uv_work_time_sec / 3600;
        UART5_Printf("[EEPROM] Save OK - UV: %lu h, Flow: %.2f L\r\n",
                     hours, eeprom_data.total_flow_liters);
    }
    else
    {
        UART5_Printf("[EEPROM] Save FAILED - Verify error!\r\n");
    }
    #endif

    // 返回验证结果: 0=成功, 1=失败
    return (verify_success == 1) ? 0 : 1;
}


/**
 * @brief  EEPROM自动保存管理
 * @param  None
 * @retval None
 * @note   在主循环中周期性调用(建议1秒一次),根据策略自动保存
 */
void app_eeprom_auto_save(void)
{
    u32 current_time = g_user_config.system_tick_sec;

    // 策略1: 定时保存 (每5分钟)
    if (current_time - g_user_config.last_save_time_sec >= EEPROM_SAVE_INTERVAL_SEC)
    {
        // 检查数据是否有变化(避免无意义的写入)
        static u32 last_saved_uv_time = 0;
        static float last_saved_flow = 0.0f;

        if (g_user_config.uv_work_time_sec != last_saved_uv_time ||
            golbal_flow.acculat != last_saved_flow)
        {
            // 数据有变化,执行保存
            u8 save_result = app_eeprom_save_data();

            if (save_result == 0)
            {
                // 保存成功,更新缓存
                last_saved_uv_time = g_user_config.uv_work_time_sec;
                last_saved_flow = golbal_flow.acculat;

                #if DEBUG_APP_ENABLE
                UART5_Printf("[EEPROM] Auto-save triggered (interval) - Success\r\n");
                #endif
            }
            else
            {
                // 保存失败,下次继续尝试
                #if DEBUG_APP_ENABLE
                UART5_Printf("[EEPROM] Auto-save triggered (interval) - Failed, will retry\r\n");
                #endif
            }
        }
    }

    // 策略2: 强制保存标志
    if (g_user_config.need_save_flag == 1)
    {
        u8 save_result = app_eeprom_save_data();

        #if DEBUG_APP_ENABLE
        if (save_result == 0)
        {
            UART5_Printf("[EEPROM] Auto-save triggered (flag) - Success\r\n");
        }
        else
        {
            UART5_Printf("[EEPROM] Auto-save triggered (flag) - Failed\r\n");
        }
        #endif
    }
}


/**
 * @brief  清除EEPROM数据
 * @param  None
 * @retval None
 * @note   清除所有历史数据,恢复出厂设置
 */
void app_eeprom_clear_data(void)
{
    u8 invalid_flag = 0xFF;

    // 将有效标志写为无效值
    EEPROM_WriteByte(EEPROM_ADDR_DATA_VALID_FLAG, invalid_flag);

    // 重置全局配置
    g_user_config.uv_work_time_sec = 0;
    g_user_config.flow_total = 0.0f;
    g_user_config.uv_lifetime_warning = 0;

    // 重置流量计累计值
    golbal_flow.acculat = 0.0f;

    #if DEBUG_APP_ENABLE
    UART5_Printf("[EEPROM] Data cleared (factory reset)\r\n");
    #endif
}


/* ===================== 新增: UV控制状态机相关EEPROM函数 ===================== */

/**
 * @brief  保存UV工作时间(小时)到EEPROM
 */
void app_eeprom_save_uv_worktime(uint32_t hours)
{
    EEPROM_WriteMulti(EEPROM_ADDR_UV_WORKTIME_HOURS, (u8*)&hours, sizeof(uint32_t));

    #if DEBUG_APP_ENABLE
    UART5_Printf("[EEPROM] UV worktime saved: %lu hours\r\n", hours);
    #endif
}

/**
 * @brief  从EEPROM读取UV工作时间(小时)
 */
uint32_t app_eeprom_read_uv_worktime(void)
{
    uint32_t hours = 0;
    EEPROM_ReadMulti(EEPROM_ADDR_UV_WORKTIME_HOURS, (u8*)&hours, sizeof(uint32_t));

    #if DEBUG_APP_ENABLE
    UART5_Printf("[EEPROM] UV worktime read: %lu hours\r\n", hours);
    #endif

    return hours;
}

/**
 * @brief  设置忽略标志位到EEPROM
 */
void app_eeprom_set_ignore_flag(uint8_t flag_id, uint8_t value)
{
    uint16_t addr = 0;

    if(flag_id == 1)
    {
        addr = EEPROM_ADDR_IGNORE_FLAG1;
    }
    else if(flag_id == 2)
    {
        addr = EEPROM_ADDR_IGNORE_FLAG2;
    }
    else
    {
        return;  // 非法flag_id
    }

    EEPROM_WriteByte(addr, value);

    #if DEBUG_APP_ENABLE
    UART5_Printf("[EEPROM] Ignore flag %d set to: %d\r\n", flag_id, value);
    #endif
}

/**
 * @brief  从EEPROM读取忽略标志位
 */
uint8_t app_eeprom_get_ignore_flag(uint8_t flag_id)
{
    uint16_t addr = 0;
    uint8_t value = 0;

    if(flag_id == 1)
    {
        addr = EEPROM_ADDR_IGNORE_FLAG1;
    }
    else if(flag_id == 2)
    {
        addr = EEPROM_ADDR_IGNORE_FLAG2;
    }
    else
    {
        return 0;  // 非法flag_id
    }

    value = EEPROM_ReadByte(addr);

    #if DEBUG_APP_ENABLE
    UART5_Printf("[EEPROM] Ignore flag %d read: %d\r\n", flag_id, value);
    #endif

    return value;
}

/**
 * @brief  清除所有UV相关EEPROM数据("更换成功"按键调用)
 */
void app_eeprom_reset_uv_data(void)
{
    uint32_t zero_hours = 0;
    uint8_t zero_flag = 0;

    // 清除UV工作时间
    EEPROM_WriteMulti(EEPROM_ADDR_UV_WORKTIME_HOURS, (u8*)&zero_hours, sizeof(uint32_t));

    // 清除"忽略1"标志位
    EEPROM_WriteByte(EEPROM_ADDR_IGNORE_FLAG1, zero_flag);

    // 清除"忽略2"标志位
    EEPROM_WriteByte(EEPROM_ADDR_IGNORE_FLAG2, zero_flag);

    // 写入UV数据有效标志位(清除后数据有效,只是清零了)
    u8 uv_valid_flag = EEPROM_UV_DATA_VALID_FLAG_VALUE;
    EEPROM_WriteByte(EEPROM_ADDR_UV_DATA_VALID_FLAG, uv_valid_flag);

    // 同步到全局变量
    g_user_config.uv_total_work_hours = 0;
    g_user_config.uv_ignore_flag1 = 0;
    g_user_config.uv_ignore_flag2 = 0;

    UART5_Printf("[EEPROM] UV data reset - Worktime & Ignore flags cleared\r\n");
}
